package com.bj58.groupbuy.action.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
public class MailSender {

    private Session session; // 
    private Properties props = System.getProperties(); // 
    private String user;
    private String password;
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    public MailSender(String smtpHost, String userName, String password) {

        props.put("mail.host", smtpHost);
        props.put("mail.localhost", smtpHost);
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.localhost", smtpHost);
        props.put("mail.smtp.auth", "true");

        // props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.socketFactory.port", "25");

        this.user = userName;
        this.password = password;
    }

    @SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
	public boolean send(MailForJMail mail,int type) throws Exception {
        try {

            session = Session.getInstance(props, new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, password);
                }
            });
            MimeMessage mimemessage = new MimeMessage(session);
            mimemessage.setFrom(new InternetAddress(mail.getFrom()));
            List<String> toList = mail.getTolist();
            if (toList.size() > 0) {
                InternetAddress[] iaToList = new InternetAddress().parse(toList.toString().replaceFirst("\\[", "").replaceFirst("\\]",""));

                mimemessage.setRecipients(Message.RecipientType.TO, iaToList);
            }
            List<String> cpList = mail.getCopyTolist();
            if (cpList.size() > 0) {
                InternetAddress[] iaToList = new InternetAddress().parse(cpList.toString().replaceFirst("\\[", "").replaceFirst("\\]",""));
                mimemessage.setRecipients(Message.RecipientType.CC, iaToList);
            }
            mimemessage.setSentDate(new Date());
            // set SUBJECT
            
            String subject = MimeUtility.encodeText(mail.getSubject(),"GBK", "b");
    		if (subject == null) {
    			subject = "";
    		} else if ((subject.startsWith("=?GBK?B?") && subject.endsWith("?="))
					|| (subject.startsWith("=?gbk?b?") && subject.endsWith("?="))){
	    		subject = this.getFromBASE64(subject.substring(8,subject.indexOf("?=") - 1));
    		} else {
    			subject = this.toChinese(subject);
    		}
    		mimemessage.setSubject(subject);

            // set TO address
            String ccmailid = mail.getCcusers();

            // set message BODY
            MimeBodyPart mimebodypart = new MimeBodyPart();
            if(type == 0){
            	 mimebodypart.setText(mail.getContent());
            }else if(type == 1){
            	mimebodypart.setContent(mail.getMultipart());
            }
            // attach message BODY
            MimeMultipart mimemultipart = new MimeMultipart();
            mimemultipart.addBodyPart(mimebodypart);
            
            // attach FILE
            ArrayList attachedFileList = mail.getAttachedFileList();
            if (attachedFileList != null) {
                for (Iterator e = attachedFileList.iterator(); e.hasNext();) {
                	File  file = new File(e.next().toString());
                	 FileDataSource ds = new FileDataSource(file);
//                    ds = new FileDataSource((File) e.next());
                    mimebodypart = new MimeBodyPart();
                    try {
                        mimebodypart.setDataHandler(new DataHandler(ds));
                    } catch (Exception exception3) {
                        throw exception3;
                    }
                    mimebodypart.setFileName(ds.getName()); // set FILENAME
                    mimemultipart.addBodyPart(mimebodypart);
                }
            }// end if
            mimemessage.setContent(mimemultipart);
            // set CC MAIL and SEND the mail

            // set CC MAIL
            if (ccmailid != null && (!ccmailid.equals(""))) {
                mimemessage.setRecipients(javax.mail.Message.RecipientType.CC,
                        ccmailid);
            }
            try {
                // send MAIL
                Transport.send(mimemessage);
                System.out.println(" Sent Successfully..........");
            } catch (Exception exception4) {
                throw exception4;
            }
        }catch (Exception e) {
            throw e;
        }
        return true;
    }
    
    
	public static String getFromBASE64(String s) {
    	if (s == null)
    		return null;
    	
    	BASE64Decoder decoder = new BASE64Decoder();
    	try {
	    	byte[] b = decoder.decodeBuffer(s);
	    	return new String(b);
    	} catch (Exception e) {
    		return null;
    	}
    }
    public static String toChinese(String strvalue) {
    	try {
    		if (strvalue == null)
    			return null;
    		else {
    			strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
    			return strvalue;
    		}
    	} catch (Exception e) {
    		return null;
    	}
    }
}
